/*
Copyright (c) 2009, Young Digital Planet SA
All rights reserved.

* Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this 
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, 
  this list of conditions and the following disclaimer in the documentation 
  and/or other materials provided with the distribution.
* Neither the name of the Young Digital Planet SA nor the names of its 
  contributors may be used to endorse or promote products derived from this 
  software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
package pl.ydp.utils
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	/**
	 * Reads binary FLV file.
	 */
	public class FLVReader extends EventDispatcher
	{
		
		public static const COMPLETE:String = "complete";
		
		protected var m_version:int;
		protected var m_totalTime:int;
		
		/**
		 * Loads and reads file which is in given location.
		 * @param path path to flv file
		 */
		public function readFile(path:String):void{
			var loader:URLLoader = new URLLoader();
			
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(Event.COMPLETE, onLoadComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
			loader.load(new URLRequest(path));
		}
		
		/**
		 * Reads file content from given byte array.
		 * @param ba flv binary data
		 */
		public function readBytes(ba:ByteArray):void{
			var dataSize:int;
			var timeStamp:int;
			
			//getting info from binary FLV file representation
			//see http://www.adobe.com/devnet/flv/pdf/video_file_format_spec_v9.pdf
			if(!(String.fromCharCode(ba.readByte()) == "F" &&
					String.fromCharCode(ba.readByte()) == "L" &&
					String.fromCharCode(ba.readByte()) == "V"))
					return;
			
			m_version = ba.readByte();
			
			//skipping the rest of the header, moving to FLV body (position 9)
			//plus 4 bytes for PreviousTagSize0 now I am in first FLV tag
			ba.position = 13;
			
			while(ba.position < ba.length){
				//skipping 1 byte of tag type
				ba.position += 1;
				dataSize = ba.readInt();
				
				//data size has 3 bytes and I read 4 so byte array must be decremented
				ba.position--;
				timeStamp = ba.readInt();
				
				timeStamp = timeStamp >> 8;
				dataSize = dataSize >> 8;
				
				//going to the next FLV tag, skippnig streamID field (3 bytes) data field and
				//PreviousTagSizeN (4 bytes)
				ba.position += dataSize + 7;
			}
			
			m_totalTime = timeStamp;
		}
		
		/**
		 * Version of flv movie file.
		 */
		public function get flvVersion():int{
			return m_version;
		}
		
		/**
		 * Duration of movie.
		 */
		public function get totalTime():int{
			return m_totalTime;
		}
		
		private function onLoadComplete(evt:Event):void{
			readBytes(ByteArray(evt.target.data));
			dispatchEvent(new Event(COMPLETE));
		}
		
		private function onLoadError(evt:IOErrorEvent):void{
			trace("FLVReader file load error: " + evt.text);
		}
	}
}